package com.song.pj.goods.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Component
public class DefaultGoodsDao implements GoodsDao{
    //1.获取连接
    @Autowired
    private DataSource datasource;
    //2.创建Statement对象（负责发送sql-sql传送器）
    @Override
    public List<Map<String, Object>> findGood() {
       Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
//        String sql="select * from tb_goods";
        try{
            conn = datasource.getConnection();

            stmt=conn.createStatement();
//3.发送sql
            String sql="select id,name,remark,createdTime from tb_goods";
            rs = stmt.executeQuery(sql);
//4.处理结果集
            List<Map<String,Object>> list = new ArrayList();
            ResultSetMetaData rsmd=rs.getMetaData();
            while(rs.next()){
//                Map<String,Object> map = new HashMap<>();
//                map.put("id",rs.getInt(1));
//                map.put("name",rs.getString(2));
//                map.put("remark",rs.getString(3));
//                map.put("createdTime",rs.getTimestamp(4));
                //方法2
//                Map<String,Object> map1 = new HashMap<>();
//                for(int i = 1;i<=rsmd.getColumnCount();i++){
//                    map.put(rsmd.getColumnLabel(i),rs.getObject(i));
//                }
                //方法3 对共性操作进行封装
                list.add(rowMap(rsmd,rs));
            }
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
            if(rs != null)try{rs.close();}catch(SQLException e){}
            if(rs != null)try{stmt.close();}catch(SQLException e){}
            if(rs != null)try{conn.close();}catch(SQLException e){}
        }
    }
    private Map<String,Object> rowMap(ResultSetMetaData rsmd,ResultSet rs) throws SQLException {
        Map<String,Object> map=new HashMap<>();
        int count=rsmd.getColumnCount();
        for(int i = 1;i<=count;i++){
            map.put(rsmd.getColumnLabel(i),rs.getObject(i));
        }
        return map;
    }
}
